const crypto = require("crypto");
class CryptoBlock {
  constructor(index, timestamp, data, precedingHash = " ") {
    this.index = index;
    this.timestamp = timestamp;
    this.data = data;
    this.precedingHash = precedingHash;
    this.hash = this.computeHash();
    this.nonce = 0;
  }
  computeHash() {
    // 将对象转换为字符串
    const objectString =
      this.index +
      this.precedingHash +
      this.timestamp +
      JSON.stringify(this.data);
    // 创建 SHA-256 加密器
    const sha256 = crypto.createHash("sha256");
    // 更新加密器的数据
    sha256.update(objectString, "utf-8");
    // 计算摘要
    return sha256.digest("hex");
  }
  proofOfWork(difficulty) {
    while (
      this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")
    ) {
      this.nonce++;
      console.log("计算次数---------", this.nonce);
      this.hash = this.computeHash();
    }
  }
}

class CryptoBlockchain {
  constructor() {
    this.blockchain = [this.startGenesisBlock()];
    this.difficulty = 1;
  }
  startGenesisBlock() {
    return new CryptoBlock(0, "01/01/2020", "Initial Block in the Chain", "0");
  }
  obtainLatestBlock() {
    return this.blockchain[this.blockchain.length - 1];
  }
  addNewBlock(newBlock) {
    // 此处应加⼊交易合法性逻辑，此处做最简单的模拟
    newBlock.precedingHash = this.obtainLatestBlock().hash;
    //newBlock.hash = newBlock.computeHash();
    newBlock.proofOfWork(this.difficulty);
    this.blockchain.push(newBlock);
  }
  checkChainValidity() {
    for (let i = 1; i < this.blockchain.length; i++) {
      const currentBlock = this.blockchain[i];
      const precedingBlock = this.blockchain[i - 1];
      if (currentBlock.hash !== currentBlock.computeHash()) {
        return false;
      }
      if (currentBlock.precedingHash !== precedingBlock.hash) return false;
    }
    return true;
  }
}

let laosijiCoin = new CryptoBlockchain();

console.log("laosijiCoin mining in progress....");

laosijiCoin.addNewBlock(
  new CryptoBlock(1, "01/01/2024", {
    sender: "张三",
    recipient: "李四",
    quantity: 50,
  })
);
laosijiCoin.addNewBlock(
  new CryptoBlock(2, "01/01/2024", {
    sender: "李四",
    recipient: "王五",
    quantity: 100,
  })
);
console.log(JSON.stringify(laosijiCoin, null, 4));
